<style lang='less' scoped>
  .tinymceBox{
    position: relative;
    width: 800px;
    .imgUploadBtn{
      position: absolute;
      top: 5px;
      right: 10px;
    }
  }
</style>


<template>
  <div class="tinymceBox">
    <div :id="id"></div>
    <el-upload
      :name='uploadConfig.name'
      :action="uploadConfig.uploadeUrl"
      :multiple="false"
      :accept="uploadConfig.accept"
      :show-file-list='false'
      :http-request='submitUpload'
      style="width:0px;height:0;overflow:hidden"
      :file-list="fileList">
      <el-button size="small" type="primary" id='imageUpload'>图片上传</el-button>
    </el-upload>

  </div>
</template>

<script>
  import browserMD5File from 'browser-md5-file'
  import { api, postUploadImg } from 'api/common'
  import {initSetting} from './config.js'

  export default {
    name: 'tinymce',
    props: ['id'],
    components:{
    },
    data() {
      return {
        editor:null,
        fileList:[],//上传图片列表
        uploadConfig:{//上传图片用的配置
          name:'upload_file',
          uploadeUrl:api.postUploadImg,//图片上传的链接
          accept:"image/png,image/gif,image/jpeg,image/jpg",
        },
        setting:initSetting,
      }
    },
    methods: {
      submitUpload(obj){
        let file = obj.file
        // console.warn('submitUpload', file)
        browserMD5File(file, (err, md5)=> {
          let fd = new FormData()
          fd.append('upload_file',file)
          fd.append('file_md5',md5)
          this.postUploadImg(fd)
        });
      },
      async postUploadImg(fd){
        try{
          let back = await postUploadImg(fd)
          back = back.data
          console.log('postUploadImg', back)
          if(back.success){
            tinymce.activeEditor.insertContent(`<img style="max-width:100%;" src='${back.file_path}' />`)
          }else{
            this.$alert('图片上传失败')
          }
        }catch(err){
          this.$alert('图片上传失败！')
          console.error(err)
        }
      },
      async checkBack(){
        if(!this.uploading){
          setTimeout(()=>{
            console.log('check uploading value', this.uploading)
            this.checkBack()
          },500)
        }else{
           return await this.uploading
        }
      },
      submit(){
        console.log('submit', tinymce.activeEditor, tinymce.activeEditor.getContent())
      }
    },
    mounted() {
      let obj ={
        selector:`#${this.id}`,
      }
      obj = Object.assign(obj, this.setting)
      window.tinymce.init(obj);
      
    },
    beforeDestroy() {
      console.log('tinymce'+this.id);
      if(window.tinymce.get(this.id)){
        window.tinymce.get(this.id).destroy()
      }
      
    }
  }
</script>


